'''
用户认证相关的API路由
'''
from flask import Blueprint, request, jsonify, g
from psycopg2.extras import RealDictCursor
from services.auth_service import (
    authenticate_user, 
    generate_token, 
    login_required, 
    admin_required,
    generate_password_hash,
    decode_token
)

# 创建蓝图
auth_bp = Blueprint('auth', __name__, url_prefix='/api/auth')

# 用户登录
@auth_bp.route('/login', methods=['POST'])
def login():
    data = request.json
    if not data:
        return jsonify({
            'status': 'error',
            'message': '无效的请求数据'
        }), 400
    
    username = data.get('username')
    password = data.get('password')
    tenant_code = data.get('tenant_code', 'default')  # 默认使用default租户
    
    if not username or not password:
        return jsonify({
            'status': 'error',
            'message': '用户名和密码不能为空'
        }), 400
    
    user = authenticate_user(username, password, tenant_code)
    
    if not user:
        return jsonify({
            'status': 'error',
            'message': '用户名、密码错误或租户不存在'
        }), 401
    
    # 生成JWT令牌
    token = generate_token(user)
    
    return jsonify({
        'status': 'success',
        'message': '登录成功',
        'data': {
            'token': token,
            'user': {
                'id': user['id'],
                'username': user['username'],
                'role': user['role'],
                'tenant_code': user['tenant_code']
            }
        }
    })

# 用户注册
@auth_bp.route('/register', methods=['POST'])
def register():
    data = request.json
    if not data:
        return jsonify({
            'status': 'error',
            'message': '无效的请求数据'
        }), 400
    
    username = data.get('username')
    password = data.get('password')
    email = data.get('email')
    tenant_code = data.get('tenant_code', 'default')  # 默认使用default租户
    
    if not username or not password:
        return jsonify({
            'status': 'error',
            'message': '用户名和密码不能为空'
        }), 400
    
    conn = g.db
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    
    # 查询租户ID
    cursor.execute(
        "SELECT id FROM tenants WHERE code = %s AND status = 'active'",
        (tenant_code,)
    )
    tenant = cursor.fetchone()
    
    if not tenant:
        return jsonify({
            'status': 'error',
            'message': '租户不存在或不可用'
        }), 400
    
    tenant_id = tenant['id']
    
    # 检查用户名是否已存在于该租户
    cursor.execute(
        "SELECT id FROM users WHERE username = %s AND tenant_id = %s",
        (username, tenant_id)
    )
    
    if cursor.fetchone():
        return jsonify({
            'status': 'error',
            'message': '用户名已存在于该租户'
        }), 400
    
    # 哈希密码
    hashed_password = generate_password_hash(password)
    
    try:
        # 创建新用户
        cursor.execute('''
        INSERT INTO users (username, password, email, tenant_id, role)
        VALUES (%s, %s, %s, %s, %s)
        RETURNING id, username, email, role, tenant_id
        ''', (username, hashed_password, email, tenant_id, 'user'))
        
        new_user = cursor.fetchone()
        conn.commit()
        
        # 为新用户创建默认设置
        cursor.execute('''
        INSERT INTO user_settings (username, user_id, preferred_ai_provider)
        VALUES (%s, %s, 'openai')
        ''', (username, new_user['id']))
        
        conn.commit()
        
        return jsonify({
            'status': 'success',
            'message': '注册成功',
            'data': {
                'user': {
                    'id': new_user['id'],
                    'username': new_user['username'],
                    'email': new_user['email'],
                    'role': new_user['role']
                }
            }
        })
    
    except Exception as e:
        conn.rollback()
        return jsonify({
            'status': 'error',
            'message': f'注册失败: {str(e)}'
        }), 500

# 获取当前用户信息
@auth_bp.route('/me', methods=['GET'])
@login_required
def get_current_user():
    user = g.current_user
    
    conn = g.db
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    
    # 获取租户信息
    cursor.execute(
        "SELECT name, code, description FROM tenants WHERE id = %s",
        (user['tenant_id'],)
    )
    tenant = cursor.fetchone()
    
    return jsonify({
        'status': 'success',
        'data': {
            'user': {
                'id': user['user_id'],
                'username': user['username'],
                'role': user['role'],
                'tenant': tenant
            }
        }
    })

# 获取所有可用租户
@auth_bp.route('/tenants', methods=['GET'])
def get_tenants():
    print("[认证API] 请求获取租户列表")
    conn = g.db
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    
    cursor.execute(
        "SELECT id, name, code, description FROM tenants WHERE status = 'active'"
    )
    tenants = cursor.fetchall()
    
    print(f"[认证API] 找到 {len(tenants)} 个可用租户")
    
    return jsonify({
        'status': 'success',
        'data': tenants
    })

# 添加调试端点，用于检查登录状态和token有效性
@auth_bp.route('/debug', methods=['GET'])
def auth_debug():
    # 获取认证信息
    auth_header = request.headers.get('Authorization')
    auth_status = {}
    
    if not auth_header:
        auth_status["has_auth_header"] = False
        auth_status["message"] = "请求中未包含认证头"
    else:
        auth_status["has_auth_header"] = True
        
        if not auth_header.startswith('Bearer '):
            auth_status["valid_format"] = False
            auth_status["message"] = "认证头格式不正确，应为 Bearer token"
        else:
            auth_status["valid_format"] = True
            token = auth_header.split(' ')[1]
            
            if not token:
                auth_status["has_token"] = False
                auth_status["message"] = "认证头中不包含token"
            elif token == "undefined" or token == "null":
                auth_status["has_token"] = False
                auth_status["message"] = "token值无效 (undefined/null)"
            else:
                auth_status["has_token"] = True
                
                # 尝试解码token
                payload = decode_token(token)
                
                if payload:
                    auth_status["valid_token"] = True
                    auth_status["user"] = {
                        "id": payload.get("user_id"),
                        "username": payload.get("username"),
                        "role": payload.get("role"),
                        "tenant_id": payload.get("tenant_id")
                    }
                    auth_status["message"] = "认证有效"
                else:
                    auth_status["valid_token"] = False
                    auth_status["message"] = "token无效或已过期"
    
    # 添加请求信息
    request_info = {
        "path": request.path,
        "method": request.method,
        "remote_addr": request.remote_addr,
        "headers": dict(request.headers)
    }
    
    return jsonify({
        'status': 'success',
        'auth_status': auth_status,
        'request_info': request_info
    })

# 管理员：创建新租户
@auth_bp.route('/tenants', methods=['POST'])
@login_required
@admin_required
def create_tenant():
    data = request.json
    if not data:
        return jsonify({
            'status': 'error',
            'message': '无效的请求数据'
        }), 400
    
    name = data.get('name')
    code = data.get('code')
    description = data.get('description')
    
    if not name or not code:
        return jsonify({
            'status': 'error',
            'message': '租户名称和编码不能为空'
        }), 400
    
    conn = g.db
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    
    # 检查编码是否已存在
    cursor.execute(
        "SELECT id FROM tenants WHERE code = %s",
        (code,)
    )
    
    if cursor.fetchone():
        return jsonify({
            'status': 'error',
            'message': '租户编码已存在'
        }), 400
    
    try:
        # 创建新租户
        cursor.execute('''
        INSERT INTO tenants (name, code, description)
        VALUES (%s, %s, %s)
        RETURNING id, name, code, description, created_at
        ''', (name, code, description))
        
        new_tenant = cursor.fetchone()
        conn.commit()
        
        return jsonify({
            'status': 'success',
            'message': '租户创建成功',
            'data': new_tenant
        })
    
    except Exception as e:
        conn.rollback()
        return jsonify({
            'status': 'error',
            'message': f'创建租户失败: {str(e)}'
        }), 500 